package com.bm.specialvehiclefordispatcher.alipay;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 生成短网址并返回
 * 
 * @author: Jerri
 * @date: 2014年3月22日下午9:58:54
 */
public class ShortUrlHelper {
	
	/**
	 * 生成短网址字符串（已经去除"http://dwz.cn/"）
	 */
	public static String createShortUrl(String longUrl) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("url", "http://www.sina.com/" + longUrl);
		String a = getJsonObjByPost("http://dwz.cn/create.php", map);
		try {
			JSONObject jsonObject = new JSONObject(a);
			String str = jsonObject.getString("tinyurl");
			String replace = str.replace("http://dwz.cn/", "");
			a = (new JSONObject(a).getString("tinyurl").replace(
					"http://dwz.cn/", ""));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return a;
	}
	
	/**
	 * 解压短网址字符串
	 */
	public static String unShortUrl(String shortUrl) {
		try {
			getJsonObjString("http://dwz.cn/" + shortUrl, "UTF-8");
			return "";
		} catch (Exception e) {
			String a = e.toString();
			return a.substring(a.indexOf("http://www.sina.com/") + 21);
		}
	}

	/**
	 * post
	 * 
	 * @param httpUrl
	 * @param param
	 * @return
	 */
	private static String getJsonObjByPost(String httpUrl,
			Map<String, String> param) {
		try {

			InputStream in = null;
			BufferedReader rd = null;
			String responseContent = "";
			HttpURLConnection url_con = null;
			try {
				URL url = new URL(httpUrl);
				url_con = (HttpURLConnection) url.openConnection();
				url_con.setRequestMethod("POST");

				url_con.setConnectTimeout(500000000);// （单位：毫秒）jdk
				url_con.setReadTimeout(500000000);// （单位：毫秒）jdk 1.5换成这个,读操作超时

				url_con.setDoOutput(true);

				OutputStream out = url_con.getOutputStream();
				
				
				String values = "";
				
				if (param != null && param.size() > 0) {
					for (Map.Entry<String, String> entry : param.entrySet()) {
						values = values + entry.getKey() + "="
								+ entry.getValue() + "&";
					}
					values = values.substring(0, values.length() - 1);
					out.write(values.getBytes("UTF-8"));
				}
				out.flush();
				out.close();

				in = url_con.getInputStream();
				rd = new BufferedReader(new InputStreamReader(in, "UTF-8"));
				String tempLine = rd.readLine();
				StringBuffer temp = new StringBuffer();
				String crlf = System.getProperty("line.separator");
				while (tempLine != null) {
					temp.append(tempLine);
					temp.append(crlf);
					tempLine = rd.readLine();
				}
				responseContent = temp.toString();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (url_con != null) {
						url_con.disconnect();
					}
					if (rd != null) {
						rd.close();
					}

					if (in != null) {
						in.close();
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			System.out.println(responseContent);

			return responseContent;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据网址，返回JSONObject对象 注：只适合请求响应为json格式网址
	 * 
	 * @param src
	 *            来源网址
	 * @param code
	 *            编码方式
	 */
	private static String getJsonObjString(String src, String code)
			throws Exception {
		InputStreamReader reader = null;
		BufferedReader in = null;
		try {
			URL url = new URL(src);
			URLConnection connection = url.openConnection();
			connection.setRequestProperty("User-Agent", "MSIE");
			connection.setConnectTimeout(10000);
			reader = new InputStreamReader(connection.getInputStream(), code);
			in = new BufferedReader(reader);
			String line = null; // 每行内容
			int lineFlag = 0; // 标记: 判断有没有数据
			StringBuilder content = new StringBuilder();
			while ((line = in.readLine()) != null) {
				content.append(line);
				lineFlag++;
			}
			return lineFlag == 0 ? null : content.toString();
		} catch (SocketTimeoutException e) {
			// System.out.println("连接超时!!!");
			throw new RuntimeException(e);
		} catch (Exception e) {
			// System.out.println("连接网址不对或读取流出现异常!!!");
			throw new RuntimeException(e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

}